package eHealth.android.Helpers;

import android.text.InputFilter;
import android.text.Spanned;

/**
 * 
 * @author Thomas Rouvinez
 * Date 15.03.2012
 * 
 * Goal : check input values for Integers in editText objects.
 *
 */
public class InputFilterMinMaxDecimal implements InputFilter {
	
	// -------------------------------------------------------------------------------------------------------
	// Variables.
	// -------------------------------------------------------------------------------------------------------
	
	/**
	 * Minimum value in double.
	 */
	private double min;
	
	/**
	 * Maximum value in double.
	 */
	private double max;
	 
	// -------------------------------------------------------------------------------------------------------
	// Constructors.
	// -------------------------------------------------------------------------------------------------------
	
	/**
	 * Constructor with minimum and maximum values input as double.
	 * @param min
	 * @param max
	 */
	public InputFilterMinMaxDecimal(double min, double max) {
		this.min = min;
		this.max = max;
	}
 
	/**
	 * Constructor with minimum and maximum values input as String.
	 * @param min
	 * @param max
	 */
	public InputFilterMinMaxDecimal(String min, String max) {
		this.min = Double.parseDouble(min);
		this.max = Double.parseDouble(max);
	}

	// -------------------------------------------------------------------------------------------------------
	// Methods.
	// -------------------------------------------------------------------------------------------------------
	
	/**
	 * Method to filter the values.
	 */
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {	
		try {
			double input = Double.parseDouble(dest.toString() + source.toString());
			if (isInRange(min, max, input))
				return null;
		} catch (NumberFormatException nfe) { }		
		return "";
	}
	
	/**
	 * Check if value is in the specified range and that the range is valid.
	 * @param a
	 * @param b
	 * @param c
	 * @return boolean if the value is in the range or not.
	 */
	private boolean isInRange(double a, double b, double c) {
		return b > a ? c >= a && c <= b : c >= b && c <= a;
	}
}
